package com.ekeyman.securecreditlib.util;

import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import com.ekeymanlib.dto.EncryptionKeys;

public class SecureCreditUtils {

	/*
	 * Encrypt using secret key encryption
	 */
	public static String encrypt(EncryptionKeys encryptionKeys, String clearText) throws Exception{
		
    	Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    	
    	SecretKeySpec encryptionKey = new SecretKeySpec(encryptionKeys.getKeyBytes(), "AES");
    	Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
	    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
	    
	    byte[] input = clearText.getBytes("UTF8");
	    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

	    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
	    ctLength += cipher.doFinal(cipherText, ctLength);
	    
	    return Base64.encodeBase64String(cipherText);
	}
	
	/*
	 * Decrypt using secret key encryption 
	 */
	public static String decrypt(EncryptionKeys encryptionKeys, String encryptedText) throws Exception{
    	Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
    	
	    SecretKeySpec decryptionKey = new SecretKeySpec(encryptionKeys.getKeyBytes(), "AES");
    	Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
    	
    	cipher.init(Cipher.DECRYPT_MODE, decryptionKey);
    	
    	byte[] cipherText = Base64.decodeBase64(encryptedText);
	    byte[] plainText = new byte[cipher.getOutputSize(cipherText.length)];
	    
	    int ptLength = cipher.update(cipherText, 0, cipherText.length, plainText, 0);
	    ptLength += cipher.doFinal(plainText, ptLength);
	    String decryptedText = new String(plainText, 0, ptLength, "UTF8");
    	
    	return decryptedText;
	}
	
}
